package com.ji.li.reactadminproexampleservice.filter;

import com.ji.li.reactadminproexampleservice.constants.SecurityConstants;
import com.ji.li.reactadminproexampleservice.utils.Utils;
import com.ji.li.reactadminproexampleservice.utils.UtilsImpl;
import com.ji.li.reactadminproexampleservice.utils.type.JwtUtils;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthorizationFilter extends BasicAuthenticationFilter{

    private final JwtUtils jwtUtils;
    private final StringRedisTemplate stringRedisTemplate;
    @Autowired
    public JwtAuthorizationFilter(
            AuthenticationManager authenticationManager, JwtUtils jwtUtils, StringRedisTemplate stringRedisTemplate) {
        super(authenticationManager);
        this.jwtUtils = jwtUtils;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws IOException, ServletException {
        System.out.println("是否走到了 JwtAuthorizationFilter");
        String token = request.getHeader(SecurityConstants.TOKEN_HEADER);
        System.out.println("传入授权token " + token);
        if (token == null) {
            SecurityContextHolder.clearContext();
            chain.doFilter(request, response);
            return;
        }
        UsernamePasswordAuthenticationToken authentication = null;
        try {
            String previousToken = stringRedisTemplate.opsForValue().get(
                    jwtUtils.setRedisKey(Integer.parseInt(jwtUtils.getU_id(token))));
            System.out.println("previousToken " + previousToken);
            if (!token.equals(previousToken)) {
                SecurityContextHolder.clearContext();
                chain.doFilter(request, response);
                return;
            }
            authentication = jwtUtils.getAuthentication(token);
        } catch (JwtException e) {
            System.out.println("Invalid jwt : " + e.getMessage());
//            logger.error("Invalid jwt : " + e.getMessage());
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        chain.doFilter(request, response);
    }
}
